package com.vf.cloud.server.colony.handler;

import com.vf.cloud.server.colony.util.ColonyUtil;

import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
 
 
//客户端业务处理类
public class NodeHandler   extends SimpleChannelInboundHandler<Object> {
 
   private  WebSocketClientHandshaker handshaker;
    ChannelPromise handshakeFuture;
 
    /**
     * 当客户端主动链接服务端的链接后，调用此方法
     *
     * @param channelHandlerContext ChannelHandlerContext
     */
    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) {
        handlerAdded(channelHandlerContext);
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("\n\t⌜⎓⎓⎓⎓⎓⎓exception⎓⎓⎓⎓⎓⎓⎓⎓⎓\n" +
              cause.getMessage());
        ctx.close();
    }
 
    public void setHandshaker(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }
    public void handlerAdded(ChannelHandlerContext ctx) {
        this.handshakeFuture = ctx.newPromise();
    }
    public ChannelFuture handshakeFuture() {
        return this.handshakeFuture;
    }
 
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        // 握手协议返回，设置结束握手
        if (!this.handshaker.isHandshakeComplete()){
            FullHttpResponse response = (FullHttpResponse)o;
            this.handshaker.finishHandshake(ctx.channel(), response);
            this.handshakeFuture.setSuccess();
           // System.out.println("WebSocketClientHandler::channelRead0 HandshakeComplete...");
            return;
        }
       else  if (o instanceof TextWebSocketFrame)
        {
               // TextWebSocketFrame textFrame = (TextWebSocketFrame)o;
                //System.out.println("WebSocketClientHandler::channelRead0 textFrame: " + textFrame.text());
        } else   if (o instanceof CloseWebSocketFrame){
          //  System.out.println("WebSocketClientHandler::channelRead0 CloseWebSocketFrame");
        }
 
    }
    
    
	/**
	 * 向客户端发送心跳
	 * 
	 * @param ctx
	 * @param evt
	 * @throws Exception
	 */
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state().equals(IdleState.READER_IDLE)) {
				ColonyUtil.sendPingForNode(ctx, System.currentTimeMillis());
			} else if (event.state().equals(IdleState.WRITER_IDLE)) {
				ColonyUtil.sendPingForNode(ctx, System.currentTimeMillis());
			} else if (event.state().equals(IdleState.ALL_IDLE)) {
				ColonyUtil.sendPingForNode(ctx, System.currentTimeMillis());
			}
		}
	}

}